﻿using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Wireframe;

namespace SampleHttpServer
{
    public sealed class HttpServer
    {
        private readonly CancellationTokenSource _cancellationTokenSource;

        public HttpServer()
        {
            _cancellationTokenSource = new CancellationTokenSource();
        }

        public void Run()
        {
            Task.Run(async () =>
                {
                    var httpListener = new HttpListener();
                    httpListener.Prefixes.Add(string.Format("http://127.0.0.1:8080/"));
                    httpListener.Start();

                    while (!_cancellationTokenSource.IsCancellationRequested)
                    {
                        HttpListenerContext context = await httpListener.GetContextAsync();
                        this.Send(new HttpRequestEvent(context));
                    }

                    httpListener.Close();
                }, _cancellationTokenSource.Token);
        }

        public void Stop()
        {
            _cancellationTokenSource.Cancel();
            _cancellationTokenSource.Dispose();
        }
    }
}